package com.example.springboot.indexsearcher;

import com.example.springboot.bean.FileBean;
import com.example.springboot.util.FileUtil;


import com.example.springboot.util.IndexUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by tangmayao on 2018/4/9.
 */
public class TestPackageClass {

    @Test
    public void test() {
        try {
            List<FileBean> fileBeans = FileUtil.getFolderFiles("E:\\idea-workbench\\index-test-files");
            int totalCount = fileBeans.size();
            int perThreadCount = 3000;

            System.out.println("查询到的数据总数是" + fileBeans.size());
            int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1);
            ExecutorService pool = Executors.newFixedThreadPool(threadCount);
            CountDownLatch countDownLatch1 = new CountDownLatch(1);
            CountDownLatch countDownLatch2 = new CountDownLatch(threadCount);

            IndexWriter indexWriter= IndexUtil.getIndexWriter("index",true);
            for (int i = 0; i < threadCount; i++) {
                int start = i * perThreadCount;
                int end = (i + 1) * perThreadCount < totalCount ? (i + 1) * perThreadCount : totalCount;
                List<FileBean> subList = fileBeans.subList(start, end);

                Runnable runnable = new FileBeanIndex(indexWriter, countDownLatch1, countDownLatch2, subList,"");
                //子线程交给线程池管理
                pool.execute(runnable);
            }

            countDownLatch1.countDown();
            System.out.println("开始创建索引");
            //等待所有线程都完成
            countDownLatch2.await();
            //线程全部完成工作
            System.out.println("所有线程都创建索引完毕");
            //释放线程池资源
            pool.shutdown();
            indexWriter.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    @Test
    public void search() {
        try {
            IndexSearcher searcher = IndexUtil.getIndexSearcher("index");
            Query query = new TermQuery(new Term("content", "public"));

            TopDocs topDocs = searcher.search(query, 10);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;

            for (ScoreDoc scoreDoc : scoreDocs) {
                Document document = searcher.doc(scoreDoc.doc);
                System.out.println("查到了:" + document.get("name"));

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}